package com.bst;

import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class BaiduTranslateService {
    private static final String API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    private static final OkHttpClient client = new OkHttpClient();
    private static final Gson gson = new Gson();

    private final String appId;
    private final String appKey;

    public BaiduTranslateService(String appId, String appKey) {
        this.appId = appId;
        this.appKey = appKey;
    }

    public TranslationResult translate(String text, String from, String to) throws IOException {
        if (text == null || text.trim().isEmpty()) {
            throw new IllegalArgumentException("翻译文本不能为空");
        }

        String salt = String.valueOf(new Random().nextInt(1000000));
        String sign = generateSign(text, salt);

        String url = API_URL + "?" +
                "q=" + URLEncoder.encode(text, StandardCharsets.UTF_8.name()) +
                "&from=" + from +
                "&to=" + to +
                "&appid=" + appId +
                "&salt=" + salt +
                "&sign=" + sign;

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("翻译请求失败: " + response.code());
            }

            String responseBody = response.body().string();
            return gson.fromJson(responseBody, TranslationResult.class);
        }
    }

    private String generateSign(String text, String salt) {
        String str = appId + text + salt + appKey;
        return md5(str);
    }

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
            
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不存在", e);
        }
    }

    public static class TranslationResult {
        public String from;
        public String to;
        public Translation[] trans_result;
        public String error_code;
        public String error_msg;

        public boolean isSuccess() {
            return error_code == null;
        }
    }

    public static class Translation {
        public String src;
        public String dst;
    }
}
